import router from "./router";
import store from "./store";
import { getToken } from "@/utils/auth";

const whiteList = ['/login']; //免登录白名单

router.beforeEach((to, from, next) => {
    if (getToken()) {
        //有token
        if (to.path === "/login") {
            //如果打开登录页面，则跳转到首页
            next({ path: "/" });
        } else {
            if (store.getters.userData === "") {
                //如果没有获取用户信息，则获取用户信息
                store.dispatch("GetUserInfo").then(() => {
                    store.dispatch("app/CreateMenuTree")//获取权限菜单
                    store.dispatch('GenerateRoutes').then(accessRoutes => {
                        router.addRoutes(accessRoutes);
                        //通过当前页面路由设置当前选中的菜单
                        accessRoutes.forEach(route => {   
                            if(route.children==undefined){
                                return
                            }
                            if (route.children.length < 1 && route.path === to.path) {
                                store.dispatch("SetActiveMenu", route);
                            } else if (route.children.length >= 1) {
                                route.children.forEach(children => {
                                    if (route.path + "/" + children.path === to.path) {
                                        store.dispatch("SetActiveMenu", route);
                                    }
                                })
                            }
                        });
                        next({...to, replace: true });
                    }).catch(res => {
                        console.log(res)
                        next({ path: '/login' });
                    })
                }).catch(res => {
                    store.dispatch('LogOut').then(() => {
                        Message.error(err)
                        next({ path: '/login' })
                      })
                })
            } else {
                next();
            }
        }
    } else {
        //没有token
        if (whiteList.indexOf(to.path) !== -1) {
            // 在免登录白名单，直接进入
            next();
        } else {
            // 否则全部重定向到登录页
            next("/login")
        }
    }
})